package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.Comment;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.utils.ErrorResult;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.MQAspect.LogConfig;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lxb哦吼吼
 * @version 1.0
 * @description: TODO
 * @date 2021/11/16 18:49
 */

@Service
public class CommentsService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFreezeService userFreezeService;


    @DubboReference
    private CommentsApi commentsApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @LogConfig(type = "0202", key = "movement", objId = "#movementId")
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = commentsApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(1, pagesize, userIds, new UserInfo());
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                //
                String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getId();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                //
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0, vos);
    }

    @LogConfig(type = "0202", key = "movement", objId = "#movementId")
    public void saveComments(String movementId, String comment) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();

        userFreezeService.checkUserStatus(3, userId);
        //2、构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        commentsApi.save(comment1);
    }

    @LogConfig(type = "0203", key = "movement", objId = "#movementId")
    public Integer likeMovement(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //2、如果已经点赞，抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.save(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    @LogConfig(type = "0206", key = "movement", objId = "#movementId")
    public Integer dislikeMovement(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //2、如果未点赞，抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.delete(comment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    @LogConfig(type = "0204", key = "movement", objId = "#movementId")
    public Integer loveMovement(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //2、如果已经喜欢，抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.save(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    @LogConfig(type = "0207", key = "movement", objId = "#movementId")
    public Integer disloveMovement(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //2、如果未点赞，抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.delete(comment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    public Integer likeComment(String CommentId) {
        Boolean hasComment = commentsApi.hasComment(CommentId, UserHolder.getUserId(), CommentType.LIKE);
        //
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(CommentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.saveComment(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + CommentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    public Integer dislikeComment(String CommentId) {
        Boolean hasComment = commentsApi.hasComment(CommentId, UserHolder.getUserId(), CommentType.LIKE);
        //
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(CommentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentsApi.deleteComment(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + CommentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }
}
